<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6" :xs="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>分类列表</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              icon="el-icon-plus"
              @click="handleAddRoot"
              v-hasPermi="['rpt:category:create']"
            >添加根分类</el-button>
          </div>
          <el-tree
            :data="categoryTree"
            :props="defaultProps"
            :expand-on-click-node="false"
            :default-expand-all="true"
            @node-click="handleNodeClick"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-plus"
                  @click.stop="() => handleAdd(data)"
                  v-hasPermi="['rpt:category:create']"
                >添加</el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-edit"
                  @click.stop="() => handleUpdate(data)"
                  v-hasPermi="['rpt:category:update']"
                >修改</el-button>
                <el-button
                  v-if="data.children.length === 0"
                  type="text"
                  size="mini"
                  icon="el-icon-delete"
                  @click.stop="() => handleDelete(data)"
                  v-hasPermi="['rpt:category:delete']"
                >删除</el-button>
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>
      
      <el-col :span="18" :xs="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{ currentCategory.categoryName || '全部报表' }}</span>
          </div>
          
          <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="报表编码" align="center" prop="reportCode" width="120" />
            <el-table-column label="报表名称" align="center" prop="reportName" :show-overflow-tooltip="true" />
            <el-table-column label="报表类型" align="center" prop="reportType" width="100">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.report_type" :value="scope.row.reportType"/>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="reportStatus" width="100">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.common_status" :value="scope.row.reportStatus"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleView(scope.row)"
                  v-hasPermi="['rpt:definition:query']"
                >查看</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleEdit(scope.row)"
                  v-hasPermi="['rpt:definition:update']"
                >编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getReportList"
          />
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 添加或修改分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item label="父分类">
          <el-input v-model="form.parentName" placeholder="无父分类" readonly v-if="form.parentId > 0"/>
          <span v-else>无</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory, getCategoryTree, getReportByCategory } from "@/api/report/category";

export default {
  name: "CategoryManagement",
  dicts: ['report_type', 'common_status'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 分类树选项
      categoryTree: [],
      // 树属性绑定
      defaultProps: {
        children: "children",
        label: "categoryName"
      },
      // 当前选中的分类
      currentCategory: {},
      // 选中报表数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 报表表格数据
      reportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: undefined
      },
      // 表单参数
      form: {
        categoryId: undefined,
        categoryName: undefined,
        parentId: 0,
        parentName: undefined,
        orderNum: 0
      },
      // 表单校验
      rules: {
        categoryName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getTreeList();
    this.getReportList();
  },
  methods: {
    /** 查询分类树列表 */
    getTreeList() {
      getCategoryTree().then(response => {
        this.categoryTree = response.data;
      });
    },
    /** 查询报表列表 */
    getReportList() {
      this.loading = true;
      const categoryId = this.currentCategory.categoryId;
      getReportByCategory(categoryId || 0).then(response => {
        this.reportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 选择树节点触发 */
    handleNodeClick(data) {
      this.currentCategory = data;
      this.queryParams.pageNum = 1;
      this.queryParams.categoryId = data.categoryId;
      this.getReportList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        categoryId: undefined,
        categoryName: undefined,
        parentId: 0,
        parentName: undefined,
        orderNum: 0
      };
      this.resetForm("form");
    },
    /** 添加根分类 */
    handleAddRoot() {
      this.reset();
      this.open = true;
      this.title = "添加根分类";
    },
    /** 添加按钮操作 */
    handleAdd(row) {
      this.reset();
      this.form.parentId = row.categoryId;
      this.form.parentName = row.categoryName;
      this.open = true;
      this.title = "添加分类";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getCategory(row.categoryId).then(response => {
        this.form = response.data;
        if (this.form.parentId > 0) {
          // 获取父分类名称
          const parentNode = this.findNodeById(this.categoryTree, this.form.parentId);
          if (parentNode) {
            this.form.parentName = parentNode.categoryName;
          }
        }
        this.open = true;
        this.title = "修改分类";
      });
    },
    /** 递归查找节点 */
    findNodeById(nodes, id) {
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i];
        if (node.categoryId === id) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const found = this.findNodeById(node.children, id);
          if (found) {
            return found;
          }
        }
      }
      return null;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.categoryId !== undefined) {
            updateCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getTreeList();
            });
          } else {
            addCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getTreeList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除分类 "' + row.categoryName + '"?').then(function() {
        return delCategory(row.categoryId);
      }).then(() => {
        this.getTreeList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.reportId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 查看报表 */
    handleView(row) {
      this.$router.push({ path: `/report/view/${row.reportId}` });
    },
    /** 编辑报表 */
    handleEdit(row) {
      this.$router.push({ path: `/report/design/edit/${row.reportId}` });
    }
  }
};
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style> 